package 码云作业;

import javax.swing.text.AbstractDocument;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class text01 {
  
	public static void readTxt(String pathname){

        File file = new File(pathname);
        if(file.exists()){
            FileInputStream fis = null;
            StringBuffer content = new StringBuffer();
            try {
                fis=new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len=fis.read(bytes);
                while (len!=-1){
                    String str = new String(bytes, 0, len,"utf-8");
                    content.append(str);
                    len = fis.read(bytes);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if(fis!=null){
                    try {
                        fis.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
            System.out.println(content.toString());
        }
    }

    public static void writeTxt(String pathname){
        File file = new File(pathname);
        String str="Hello World";
        FileOutputStream fos = null;
        if(!file.exists()){
            try {
                file.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }

        }
            try {
                fos = new FileOutputStream(file,true);
                byte[] bytes = str.getBytes("utf-8");
                fos.write(bytes);
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }

    public static void main(String[] args) {

        String pathname = "doc/test.txt";
        writeTxt(pathname);
        readTxt(pathname);
    }
}
